#include "daemon_process.h"
#include "thirdparty/log/log.h"
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

int daemon_process_init(DaemonProcess *dp, const char *part)
{
    dp->exec = "/usr/bin/gateway";
    dp->argv[0] = dp->exec;
    dp->argv[1] = malloc(strlen(part) + 1);
    if (!dp->argv[1])
    {
        log_error("daemon_process_init: malloc failed");
        return -1;
    }
    strcpy(dp->argv[1], part);
    dp->argv[2] = NULL;
    dp->pid = -1;

    return 0;
}

int daemon_process_start(DaemonProcess *dp)
{
    if (dp->pid > 0)
    {
        pid_t result = waitpid(dp->pid, NULL, WNOHANG);
        if (result == 0)
        {
            return -1;
        }
    }

    log_trace("Gateway %s starting...", dp->argv[1]);
    dp->pid = fork();
    if (dp->pid == -1)
    {
        log_error("daemon_process_start: fork failed");
        return -1;
    }

    if (dp->pid == 0)
    {
        int result = execve(dp->exec, dp->argv, __environ);
        if (result < 0)
        {
            log_error("daemon_process_start: execve failed");
            exit(EXIT_FAILURE);
        }
    }

    return 0;
}

int daemon_process_stop(DaemonProcess *dp)
{
    // 给子进程发送信号
    if (dp->pid > 0)
    {
        kill(dp->pid, SIGTERM);
        waitpid(dp->pid, NULL, 0);
        dp->pid = -1;
    }

    return 0;
}

int daemon_process_free(DaemonProcess *dp)
{
    if (dp->argv[1])
    {
        free(dp->argv[1]);
        dp->argv[1] = NULL;
    }
    return 0;
}
